module manager {

    import AdPage = page.AdPage;

    export class AdManager extends egret.Sprite {

        public static LOAD_CONFIG_COMPLETE: string = "load_game_config_complete";

        public static readonly SHARE_TYPE: number = 1;

        public static readonly VIDEO_TYPE: number = 2;

        private token = "";

        public audit: number = 0;

        public float_ad = [];

        public float_ad_idx: number = 0;

        public float_ad2 = [];

        public float_ad2_idx: number = 0;

        public more_game_ad = [];

        public more_game_ad_idx: number = 0;

        public love_game_ad: Ad;

        public love_game_ad_idx: number = 0;

        public wx_banner: Array<string>;

        public wx_video: Array<string>;

        public banner_type: number;

        public banner_ad: Array<Ad>;

        public banner_ad_idx: number = 0;

        public switch_time: number;

        public relive_time: number;

        public subscribe_text: string;

        public share: Share;

        private isLoadComplete: boolean = false;

        private videoAd: RewardedVideoAd;

        public drawer_ad = [];

        public drawer_ad_idx: number = 0;

        public get_type = "";

        public ad_percent: number;

        public bannerAd: BannerAd;

        private realBannerAdHeight: number;

        private realBannerAdWidth: number;

        private options = {};

        private data  = {
            audit: null,
            config: null
        };

        public constructor(gameToken: string) {
            super();
            this.token = gameToken;
        }

        public isChecking(): boolean {
            // return true;
            return this.audit > 0;
        }

        public showBanner(isShow: boolean): void {
            if (this.adPage == null) {
                this.adPage = new page.AdPage();
                this.adPage.show(isShow);
            }
        }

        public showBannerAd(): void {
            if (this.banner_type == 0 || this.wx_banner == null || this.wx_banner.length < 1) {
                if (this.isChecking()) {
                    return;
                }
                this.showPrivateAd(true);
            } else {
                this.showPrivateAd(false);
                let adHeight: number = 20;
                if (this.bannerAd == null) {
                    let wxBanner: string = this.wx_banner[0];
                    egret.log("wxBanner:", wxBanner);
                    let systemInfo = SystemManager.info;
                    egret.log("systemInfo:", systemInfo);
                    let that = this;
                    let adWidth: number = systemInfo.screenWidth / 4;
                    this.bannerAd = wx.createBannerAd({
                        adUnitId: wxBanner,
                        style: {
                            left: 0,
                            top: systemInfo.screenHeight - adHeight,
                            width: adWidth,
                            height: adHeight,
                        }
                    });
                    this.bannerAd.onResize(function (res: any) {
                        egret.log("width:", res.width);
                        egret.log("height:", res.height);
                        egret.log("adUnitId:", that.bannerAd.adUnitId);
                        that.setRealBannerAdSize(res.width, res.height);
                        that.bannerAd.style.top = systemInfo.screenHeight - res.height;
                        that.bannerAd.style.left = (systemInfo.screenWidth - res.width) / 2;
                    });
                }
                this.bannerAd.show();
                if (this.bannerAd.onError) {
                    this.bannerAd.onError(function (res: any) {
                        console.log("流量主拉取异常：", res);
                    });
                }
            }
        }


        public hasBanner(): boolean {
            let bannerAd = this.banner_ad;
            if (bannerAd != null && bannerAd.length > 0) {
                return true;
            }
            let wxBanner = this.wx_banner;
            if (wxBanner != null && wxBanner.length > 0) {
                return true;
            }
            return false;
        }

        public adPage: page.AdPage;

        private showPrivateAd(need_banner: boolean): void {
            // return;
            // if (this.adPage == null) {
            //     this.adPage = new page.AdPage();
            // }
            // egret.log("showPrivateAd");
            // manager.GameManager.getInstance().getUIManager().addAdWidget(this.adPage);
            // this.adPage.show(need_banner);
            // this.adPage.addEventListener(AdPage.BANNER_RESIZE, this.onBannerResize, this);

            if(this.adPage == null){
                this.adPage = new page.AdPage();
                manager.GameManager.getInstance().getUIManager().addAdWidget(this.adPage);
                this.adPage.show(need_banner);
                this.adPage.addEventListener(AdPage.BANNER_RESIZE, this.onBannerResize, this);
            }
        }

        private onBannerResize(eve: egret.Event): void {
            let bannerRealHeight: number = eve.data;
            DisplayManager.setRealBannerAdSize(manager.DisplayManager.STAGE_WIDTH, bannerRealHeight, "banner");
        }

        private setRealBannerAdSize(width: number, height: number): void {
            this.realBannerAdWidth = width;
            this.realBannerAdHeight = height;
            DisplayManager.setRealBannerAdSize(width, height, "wxa");
        }

        public hideBannerAd(): void {
            if (this.bannerAd != null) {
                this.bannerAd.hide();
            }
            if (this.adPage != null) {
                this.adPage.visible = false;
            }
        }

        public shareRelive() {

        }

        public async showVideoAd(): Promise<any> {
            egret.log("准备播放视频");
            if (this.wx_video != null && this.wx_video.length > 0) {
                egret.log("开始播放视频");
                this.videoAd = wx.createRewardedVideoAd({adUnitId: this.wx_video[0]});
                this.videoAd.onClose(this.onVideoAdClose);
                this.videoAd.onError(this.onVideoPlayError);
                await this.videoAd.load();
                await this.videoAd.show();
            }
        }

        private onVideoPlayError(res): void {
            let event = new egret.Event(AdManager.VIDEO_PLAY_ERROR);
            GameManager.getInstance().adManager.dispatchEvent(event);
            let title: string = "今日视频已用尽";
            wx.showToast({title: title, icon: "none"})
        }

        public static readonly VIDEO_AD_CLOSE: string = "video_ad_close";
        public static readonly VIDEO_PLAY_ERROR: string = "video_play_error";

        private onVideoAdClose(res: { isEnded: boolean }): void {
            egret.log("是否观看完毕:", res.isEnded);
            let event = new egret.Event(AdManager.VIDEO_AD_CLOSE, false, false, res);
            GameManager.getInstance().getAdManager().dispatchEvent(event);

            if (!res.isEnded) {
                wx.showToast({title: "视频未播放完", icon: "none"})
            }
        }

        public hideVideoAd(): void {

        }

        private getUserInfo() {
            egret.log("开始从本地恢复用户数据");
            let that = this;
            let data = wx.getStorageSync(StatisticsManager.login_key);
            if (data) {
                wx.checkSession({
                    success: function () {
                        manager.GameManager.getInstance().getUserManager().loginData.session_3rd = data["session_3rd"];
                        manager.GameManager.getInstance().getUserManager().getCoin();
                        that.getConfig(data["session_3rd"], that.options["wxa_tunnel"]);
                    },
                    fail: function () {
                        console.log("wx.checkSession fail");
                        that.getUserSession();
                    },
                    complete: function () {
                    }
                })
            } else {
                console.log("no local data");
                that.getUserSession();
            }
        }

        private getUserSession() {
            let that = this;
            let query = wx.getLaunchOptionsSync().query || {}
            wx.login({
                success: function (login_res) {
                    let post_data = {
                        token: that.token,
                        code: login_res.code,
                        tunnel_id: query["wxa_tunnel"] || "",
                        inviter_uid: query["inviter_uid"] || ""
                    }
                    wx.request({
                        url: 'https://2zhuji.cn/index.php?g=WxaGame&m=Login&a=login',
                        data: post_data,
                        header: "application/x-www-form-urlencoded",
                        method: "GET",
                        dataType: "json",
                        success: function (res) {
                            if (res.data.status == 1001) {
                                if (res.data.userInfo) {
                                    let data = res.data;
                                    let storeData = {
                                        session_3rd: data.session_3rd,
                                        host: {
                                            userinfo: data.userInfo,
                                            user: data.user
                                        }
                                    };
                                    wx.setStorage({
                                        key: UserManager.login_key,
                                        data: storeData,
                                        success: function (res) {
                                        },
                                        fail: function (res) {
                                        },
                                        complete: function (res) {
                                        }
                                    });
                                }
                                manager.GameManager.getInstance().getUserManager().loginData.session_3rd = res.data.session_3rd;
                                manager.GameManager.getInstance().getUserManager().getCoin();
                                that.getConfig(res.data.session_3rd, that.options["wxa_tunnel"]);
                            } else {
                                that.getConfig("", "");
                            }
                        },
                        fail: function () {
                            that.getConfig("", "");
                        },
                        complete: function () {
                        }
                    });
                },
                fail: function () {
                    that.getConfig("", "");
                },
                complete: function () {
                }
            });
        }


        public loadConfig() {
            if (!GameManager.isProduct) {
                this.dispatchEvent(new egret.Event(AdManager.LOAD_CONFIG_COMPLETE));
                return;
            }
            let options = wx.getLaunchOptionsSync();
            this.options = options["query"] || {};
            this.getUserInfo();
        }

        private getConfig(session_3rd: any, tunnel_id: any) {
            egret.log("加载广告设置");
            let request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            let url = "https://2zhuji.cn/index.php?g=Wap&m=WxaGame&a=get_config&token=" + this.token;
            if (tunnel_id && session_3rd) url += "&tunnel_id=" + tunnel_id + "&session_3rd=" + session_3rd;
            egret.log("游戏配置:", url);
            request.open(url, egret.HttpMethod.GET);
            request.send();
            request.addEventListener(egret.Event.COMPLETE, this.onLoadComplete, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onPostIOError, this);
            request.addEventListener(egret.ProgressEvent.PROGRESS, this.onPostProgress, this);
        }

        private onLoadComplete(event: egret.Event): void {

            let request = <egret.HttpRequest>event.currentTarget;
            let data = JSON.parse(request.response);
            egret.log("加载广告设置完成:", data);
            this.data.config = data;
            this.setConfig();
        }

        private setConfig(): void {
            let data = this.data.config;
            let audit = manager.GameManager.auditData;
            egret.log("wx_banner:", data["set"]["wx_bannner"]);

            this.float_ad = audit.floatad ? [audit.floatad] : [];
            this.float_ad2 = audit.gameFloatad || [];
            this.more_game_ad = [audit.moread];
            this.drawer_ad = audit.drawerad;
            this.setWxaAd();

            this.switch_time = data["set"]["switch_time"];
            this.relive_time = data["set"]["relive_time"];
            this.subscribe_text = data["set"]["subscribe_text"];
            this.share = data["set"]["share"];
            this.get_type = data["set"]["get_type"];
            this.ad_percent = Number(data["set"]["ad_percent"]) || 0;
            // this.audit = audit.data == "3003" ? 1 : 0;

            this.audit = parseInt(data["audit"]);

            this.isLoadComplete = true;
            this.dispatchEvent(new egret.Event(AdManager.LOAD_CONFIG_COMPLETE));
        }

        private setWxaAd() {
            var ads = manager.GameManager.auditData.adad, banner = [], video = [], ad = [];
            if (!ads || !ads.length) return;
            for (var i = 0; i < ads.length; i++) {
                if (ads[i].type == "3") {
                    banner.push(ads[i].ad_code);
                } else if (ads[i].type == "5") {
                    video.push(ads[i].ad_code);
                } else {
                    ad.push(ads[i]);
                }
            }
            if (banner.length) this.wx_banner = banner;
            if (video.length) this.wx_video = video;
            if (ad.length) this.banner_ad = ad;
            this.banner_type = banner.length || video.length ? 1 : 0;
        }

        public showAd(type:string, ad = null) {
            console.log("showAd: ", type, " ", ad);
            let adManager = GameManager.getInstance().getAdManager();
            let ads = adManager[type] || [];
            let idx: number = (adManager[type + '_idx']) % ads.length;
            ad = ad || (type == "banner_ad" ? adManager[type]&&adManager[type][0] : ads[idx]);
            let SDKVersion = wx.getSystemInfoSync().SDKVersion;
            console.log("showAd 2: ", ad);
            if(!ad){
                return;
            }
            console.log(111)
            GameManager.getInstance().statisticManager.adStats(1, this.getAdType(type), ad);
            if(ad.type == 2 && (helper.Helper.compareVersion(SDKVersion,'2.0.3') === 1)) {
                //客服
                let session = ad.session&&ad.session.indexOf("y1yad_")==0?ad.session:"y1yad_"+ad.session||"";
                wx.openCustomerServiceConversation({
                    sessionFrom:session,
                    showMessageCard:ad.showMessageCard||false,
                    sendMessageTitle:ad.sendMessageTitle||"",
                    sendMessagePath:ad.sendMessagePath||"",
                    sendMessageImg:ad.sendMessageImg||"",
                    complete:res=>{
                        console.log("ad "+type+" session "+ad.session+":",res);
                    }
                });
            } else if (ad.type == 1 && ad.appid && (helper.Helper.compareVersion(SDKVersion,'2.2.0') === 1)) {
                //进入其他小程序
                manager.StatisticsManager.goToMiniPro({appid: ad.appid, path: ad.path}, null);
                manager.GameManager.getInstance().statisticManager.statusPv(ad.appid, ad.path, 0);
            } else if (ad.ad_img) {
                helper.Helper.previewImg(ad.ad_img);
            }
        }

        private getAdType(type) {
            switch (type) {
                case "float_ad":
                    return "float";
                case "float_ad2":
                    return "gameFloat";
                case "banner_ad":
                    return "ad";
                case "more_game_ad":
                    return "more";
                case "drawer_ad":
                    return "drawer";
            }
        }

        public getShareTitle(): string {
            let idx: number = manager.RandomManager.getRandRange(0, this.share.title.length - 1);
            return this.share.title[idx];
        }

        public getScoreShareTitle(): string {
            let idx: number = manager.RandomManager.getRandRange(0, this.share.score_title.length - 1);
            return this.share.score_title[idx];
        }

        public getShareImg(): string {
            let idx: number = manager.RandomManager.getRandRange(0, this.share.img.length - 1);
            let img: string = this.share.img[idx];
            egret.log("分享图片地址>>>this.share.img[idx]:", idx, img);
            return img;
        }

        public getShareInfo(): ShareInfo {
            let idx: number = manager.RandomManager.getRandRange(0, this.share.img.length - 1);
            let img: string = this.share.img[idx];
            let title: string = this.share.title[idx];
            let info = new ShareInfo();
            info.title = title;
            info.img = img;
            return info;
        }

        private onPostIOError(event: egret.IOErrorEvent): void {
            wx.showToast({
                title: "配置加载失败",
                icon: "none",
            });
        }

        private onPostProgress(event: egret.ProgressEvent): void {
            console.log("post progress : " +
                Math.floor(100 * event.bytesLoaded / event.bytesTotal) + "%");
        }

        public switchVideoOrShareType(): number {
            let adManager: manager.AdManager = manager.GameManager.getInstance().adManager;
            // let getType: number = parseInt(manager.GameManager.getInstance().adManager.get_type);
            // if (getType == manager.AdManager.SHARE_TYPE) {
            //     return manager.AdManager.SHARE_TYPE;
            // } else {
            //     if (adManager.wx_video != null && adManager.wx_video.length > 0) {
            //         let percent: number = parseInt(adManager.ad_percent);
            //         if (100 * Math.random() > percent) {
            //             return manager.AdManager.SHARE_TYPE;
            //         } else {
            //             return manager.AdManager.VIDEO_TYPE;
            //         }
            //     } else {
            //         return manager.AdManager.SHARE_TYPE;
            //     }
            // }
            if (adManager.wx_video != null && adManager.wx_video.length > 0) {
                let percent: number = Number(adManager.ad_percent);
                if (percent > 100 * Math.random()) {
                    return manager.AdManager.SHARE_TYPE;
                } else {
                    return manager.AdManager.VIDEO_TYPE;
                }
            } else {
                return manager.AdManager.SHARE_TYPE;
            }
        }

    }

    export interface IAdLoaded {
        onAdLoaded(adComponent: AdManager): void;
    }

    export interface IAd {
        onAdLoaded(adComponent: AdManager): void;
    }

    export class Share {
        public title: Array<string>;

        public score_title: Array<string>;

        public img: Array<string>;

        public getTitle(): string {
            let idx: number = manager.RandomManager.getRandRange(0, this.score_title.length - 1);
            return this.score_title[idx];
        }

        public getImg(): string {
            let idx: number = manager.RandomManager.getRandRange(0, this.img.length - 1);
            return this.img[idx];
        }

    }

    export class ShareInfo {
        public title: string;
        public img: string;
    }

    export class Ad {
        public img: string;
        public type: number;
        public session: string;
        public poster: Array<Poster>;

    }

    export class Poster {
        public appid: string;
        public icon: string;
        public path: string;
        public preview: number;
        public img: string;
    }

}